package com.service.link;

import com.domain.HttpResponse;
import com.domain.ex.BizException;
import com.domain.ex.Codes;
import com.mapper.self.LinkMapper;
import com.pojo.ShLink;
import com.utils.ValidatorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * Created by Huoyunren on 2016-08-09.
 */
@Service
public class LinkServiceImpl implements LinkService {

  @Autowired
  private LinkMapper linkMapper;


  @Override
  public Object saveOrUpdate(Integer linkId, String linkName, String linkUrl, String linkDesc) {

    if (!ValidatorUtils.validatorUrl(linkUrl)){
      throw BizException.create(Codes.SystemDeclare,"url地址无效");
    }
    ShLink link = new ShLink();
    link.setId(linkId);
    link.setLinkName(linkName);
    link.setLinkUrl(linkUrl);
    link.setLinkDesc(linkDesc);
    link.setCreateTime(new Date());
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    String email = request.getSession().getAttribute("email").toString();
    link.setEmail(email);
    linkMapper.saveOrUpdate(link);
    return HttpResponse.create(Codes.OK, "", link);
  }

  @Override
  public List<ShLink> list() {

    return linkMapper.list();
  }

  @Override
  public Object del(Integer linkId) {
    linkMapper.del(linkId);
    return HttpResponse.OK();
  }


  @Override
  public Object incrClickCount(Integer linkId) {
    linkMapper.incrClickCount(linkId);
    return HttpResponse.OK();
  }
}
